<template>
    <div>
        <Breadcrumb name1="商品管理" name2="添加商品"></Breadcrumb>
        <el-card>
            <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
            <el-steps :active="activeIndex-0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <el-tabs tab-position="left"  v-model="activeIndex" @tab-click="tabClicked"
            :before-leave="beforeTabsLeave">
                <el-tab-pane label="基本信息" name="0">
                    <el-form :model="addGoodsForm" :rules="addGoodsFormRules" ref="addGoodsFormRef">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addGoodsForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="addGoodsForm.goods_price" type="number" min="0"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="addGoodsForm.goods_weight" type="number" min="0"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="addGoodsForm.goods_number" type="number" min="0"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-cascader
                            v-model="addGoodsForm.goods_cat"
                            :options="catList"
                            :props="{ expandTrigger: 'hover',children:'children',value: 'cat_id',label: 'cat_name',}"
                            >
                            </el-cascader>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="商品参数" name="1">
                    <el-form>
                        <el-form-item :label="item.attr_name" v-for="item in manyData" :key="item.attr_id">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox :label="item2" v-for="(item2, index2) in item.attr_vals" :key="index2" border></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="商品属性" name="2">
                    <el-form>
                        <el-form-item :label="item.attr_name" v-for="item in onlyData" :key="item.attr_id">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="3">
                    <el-upload
                        :action="uploadURL"
                        :on-preview="handlePreview"
                        :on-remove="handleRemove"
                        :on-success="handleSuccess"
                        :headers="headerObj"
                        list-type="picture">
                        <el-button size="small" type="primary">点击上传</el-button>
                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品内容" name="4">
                    <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
                    <el-button type="primary" class="btnAdd" @click="addGoods">添加商品</el-button>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 图片预览对话框 -->
        <el-dialog
            title="图片预览"
            :visible.sync="previewShow"
            width="50%">
            <img :src="previewPath" alt="" class="previewClass">
        </el-dialog>
    </div>
</template>

<script>
import { request } from '../../../api/axios'
import Breadcrumb from "../components/Breadcrumb.vue"
export default {
    name:"addGoods",
    components:{ Breadcrumb },
    data(){
        return{
            activeIndex:0,

            // 新增的表单
            addGoodsForm:{
                goods_name:"",
                goods_price:0,
                goods_number:0,
                goods_weight:0,
                goods_introduce:"",
                goods_cat: [],
                pics:[],
                attrs:[]
            },
            // 添加商品的验证规则对象
            addGoodsFormRules: {
                goods_name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' }
                ],
                goods_price: [
                    { required: true, message: '请输入商品价格', trigger: 'blur' }
                ],
                goods_weight: [
                    { required: true, message: '请输入商品重量', trigger: 'blur' }
                ],
                goods_number: [
                    { required: true, message: '请输入商品数量', trigger: 'blur' }
                ],
                goods_cat: [
                    { required: true, message: '请选择商品分类', trigger: 'blur' }
                ]
            },

            // 获取到的商品分类选项的数据
            catList:[],

            // 商品参数
            manyData: [],
            onlyData:[],
            // 图片地址
            uploadURL:"http://127.0.0.1:8888/api/private/v1/upload",
            headerObj: {
                Authorization: window.sessionStorage.getItem('token')
            },
            // 图片预览地址
            previewPath:"",
            // 图片预览框的显示与隐藏
            previewShow:false
        }
    },
    created() {
        this.getCateList()
    },
    methods:{
        // 获取到商品分类选项的数据
        getCateList(){
            request("get","categories")     //1.6.1
            .then(res =>{
                console.log(res)
                this.catList=res.data
            })
        },

        tabClicked () {
            console.log(this.activeIndex)
            console.log(this.addGoodsForm.goods_cat)
            if (this.activeIndex === '1') {
                request("get","categories/"+this.addGoodsForm.goods_cat[2]+"/attributes", {sel:"many"})
                .then( res => {
                    console.log(res)
                    res.data.forEach(item => {
                        if(item.attr_vals.length === 0){
                            item.attr_vals = []
                        }
                        else{
                            item.attr_vals = item.attr_vals.split(' ')
                        }
                    })
                    this.manyData =res.data
                })
            }
            else if (this.activeIndex === '2') {
                request("get","categories/"+this.addGoodsForm.goods_cat[2]+"/attributes", {sel:"only"})
                .then( res =>{
                    console.log(res)
                    this.onlyData = res.data
                })
            }
        },

        beforeTabsLeave(activeName, oldActiveName) {
            if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
                this.$message.error('请选择商品分类')
                return false
            }
        },

        // 图片上传
        handleSuccess(response){
            const picInfo = { pic: response.data.tmp_path }
            this.addGoodsForm.pics.push(picInfo)
        },
        // 图片预览
        handlePreview(file) {
            this.previewPath = file.response.data.url
            this.previewShow = true
        },
        // 点击移除图片
        handleRemove(file) {
            // 1-获取将要删除的图片的临时路径
            const filePath = file.response.data.tmp_path
            // 2-从pics数组中删除图片路径
            this.addGoodsForm.pics.forEach((item,index) => {
                if(item.pic==filePath){
                    this.addGoodsForm.pics.splice(index,1)
                }
            })
        },

        // 添加商品
        addGoods(){
            this.$refs.addGoodsFormRef.validate(valid => {
                if(!valid){
                    return this.$message.error('请填写必要的表单项目')
                }
                // 发送请求前处理各项参数
                this.addGoodsForm.goods_cat = this.addGoodsForm.goods_cat.join(',')
                // 动态参数
                this.manyData.forEach(item => {
                    const newInfo = {
                        attr_id: item.attr_id,
                        attr_value: item.attr_vals.join(' ')
                    }
                    this.addGoodsForm.attrs.push(newInfo)
                })
                // 处理静态属性
                this.onlyData.forEach(item => {
                    const newInfo = {
                        attr_id: item.attr_id,
                        attr_vals: item.attr_vals
                    }
                    this.addGoodsForm.attrs.push(newInfo)
                })
                // 发送请求
                console.log(this.addGoodsForm)
                request("post","goods",this.addGoodsForm)   //1.8.2
                .then( res => {
                    console.log(res)
                    if(res.meta.status==201){
                        this.$message.success('添加商品成功')
                        this.$router.push("/goods")
                    }else(this.$message.error('添加商品失败'))
                })
            })
        }
    }
}
</script>

<style scoped>
.el-steps{
    margin: 15px;
}
.previewClass{
    width: 100%;
}
.quill-editor{
    height: 300px;
}
.btnAdd{
    margin-top: 80px;
}
</style>